#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from app import create_app
from models import db, Problem
import json

def add_mixed_problems():
    """添加各种题型的例题"""
    app = create_app()
    
    with app.app_context():
        # 定义各种题型的例题
        mixed_problems_data = [
            # 选择题例题
            {
                "title": "Python基础语法选择题",
                "description": "以下哪个是Python中的正确变量命名？",
                "type": "choice",
                "answer": "B",
                "options": json.dumps([
                    "2variable",
                    "my_variable",
                    "class",
                    "def"
                ]),
                "difficulty": "easy",
                "points": 10,
                "time_limit": 60,
                "memory_limit": 64,
                "language": "python",
                "created_by": 1,
                "status": "active"
            },
            {
                "title": "数据结构选择题",
                "description": "以下哪种数据结构最适合实现栈（Stack）？",
                "type": "choice",
                "answer": "A",
                "options": json.dumps([
                    "数组或链表",
                    "二叉树",
                    "图",
                    "哈希表"
                ]),
                "difficulty": "medium",
                "points": 15,
                "time_limit": 60,
                "memory_limit": 64,
                "language": "python",
                "created_by": 1,
                "status": "active"
            },
            
            # 填空题例题
            {
                "title": "Python语法填空题",
                "description": "在Python中，用于定义函数的关键字是____，用于定义类的关键字是____。",
                "type": "blank",
                "answer": "def,class",
                "difficulty": "easy",
                "points": 10,
                "time_limit": 60,
                "memory_limit": 64,
                "language": "python",
                "created_by": 1,
                "status": "active"
            },
            {
                "title": "算法复杂度填空题",
                "description": "快速排序的平均时间复杂度是____，最坏时间复杂度是____。",
                "type": "blank",
                "answer": "O(nlogn),O(n²)",
                "difficulty": "medium",
                "points": 15,
                "time_limit": 60,
                "memory_limit": 64,
                "language": "python",
                "created_by": 1,
                "status": "active"
            },
            
            # 简答题例题
            {
                "title": "面向对象编程简答题",
                "description": "请简要说明面向对象编程的三大特性（封装、继承、多态）的含义和作用。",
                "type": "short",
                "answer": "封装：将数据和操作数据的方法绑定在一起，对外部隐藏实现细节。继承：子类可以继承父类的属性和方法，实现代码重用。多态：同一个接口可以有多种不同的实现方式。",
                "difficulty": "medium",
                "points": 20,
                "time_limit": 300,
                "memory_limit": 64,
                "language": "python",
                "created_by": 1,
                "status": "active"
            },
            {
                "title": "算法设计简答题",
                "description": "请描述如何使用深度优先搜索（DFS）算法遍历一棵二叉树，并说明其时间复杂度。",
                "type": "short",
                "answer": "深度优先搜索遍历二叉树的过程：1. 访问根节点 2. 递归遍历左子树 3. 递归遍历右子树。时间复杂度为O(n)，其中n是树中节点的数量，因为每个节点都会被访问一次。",
                "difficulty": "hard",
                "points": 25,
                "time_limit": 300,
                "memory_limit": 64,
                "language": "python",
                "created_by": 1,
                "status": "active"
            },
            
            # 编程题例题
            {
                "title": "冒泡排序",
                "description": """实现冒泡排序算法，对给定的整数数组进行升序排序。

冒泡排序的基本思想是：
1. 比较相邻的两个元素，如果第一个比第二个大，则交换它们
2. 对每一对相邻元素执行同样的操作，从开始第一对到结尾的最后一对
3. 重复以上步骤，直到没有任何一对数字需要交换

示例：
输入：[64, 34, 25, 12, 22, 11, 90]
输出：[11, 12, 22, 25, 34, 64, 90]""",
                "type": "code",
                "answer": None,
                "test_cases": json.dumps([
                    {
                        "input": "[64, 34, 25, 12, 22, 11, 90]",
                        "output": "[11, 12, 22, 25, 34, 64, 90]"
                    },
                    {
                        "input": "[5, 2, 4, 6, 1, 3]",
                        "output": "[1, 2, 3, 4, 5, 6]"
                    }
                ]),
                "difficulty": "medium",
                "points": 20,
                "time_limit": 1000,
                "memory_limit": 64,
                "language": "python",
                "created_by": 1,
                "status": "active"
            },
            
            # 片段编程题例题
            {
                "title": "完成二分查找函数",
                "description": """请完成以下二分查找函数中的缺失部分。二分查找要求数组必须是已排序的。

```python
def binary_search(arr, target):
    left = 0
    right = len(arr) - 1
    
    while left <= right:
        mid = (left + right) // 2
        
        # 请在这里填写缺失的代码
        # 如果找到目标值，返回其索引
        # 如果目标值小于中间值，更新right
        # 如果目标值大于中间值，更新left
    
    return -1  # 如果没找到，返回-1
```

示例：
输入：arr = [1, 3, 5, 7, 9, 11, 13, 15], target = 7
输出：3

输入：arr = [1, 3, 5, 7, 9, 11, 13, 15], target = 10
输出：-1""",
                "type": "code",
                "answer": "if arr[mid] == target:\n    return mid\nelif arr[mid] > target:\n    right = mid - 1\nelse:\n    left = mid + 1",
                "test_cases": json.dumps([
                    {
                        "input": "[1, 3, 5, 7, 9, 11, 13, 15]\n7",
                        "output": "3"
                    },
                    {
                        "input": "[1, 3, 5, 7, 9, 11, 13, 15]\n10",
                        "output": "-1"
                    }
                ]),
                "difficulty": "medium",
                "points": 25,
                "time_limit": 1000,
                "memory_limit": 64,
                "language": "python",
                "created_by": 1,
                "status": "active"
            },
            {
                "title": "完成链表反转函数",
                "description": """请完成以下链表反转函数中的缺失部分。

```python
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

def reverse_list(head):
    prev = None
    current = head
    
    while current is not None:
        # 请在这里填写缺失的代码
        # 保存下一个节点
        # 反转当前节点的指针
        # 移动prev和current指针
    
    return prev
```

示例：
输入：1 -> 2 -> 3 -> 4 -> 5
输出：5 -> 4 -> 3 -> 2 -> 1""",
                "type": "code",
                "answer": "next_node = current.next\ncurrent.next = prev\nprev = current\ncurrent = next_node",
                "test_cases": json.dumps([
                    {
                        "input": "[1,2,3,4,5]",
                        "output": "[5,4,3,2,1]"
                    },
                    {
                        "input": "[1,2]",
                        "output": "[2,1]"
                    }
                ]),
                "difficulty": "hard",
                "points": 30,
                "time_limit": 1000,
                "memory_limit": 64,
                "language": "python",
                "created_by": 1,
                "status": "active"
            }
        ]
        
        # 检查是否已存在相同标题的题目
        existing_titles = [p.title for p in Problem.query.all()]
        new_problems = []
        
        for problem_data in mixed_problems_data:
            if problem_data["title"] not in existing_titles:
                problem = Problem(**problem_data)
                db.session.add(problem)
                new_problems.append(problem_data["title"])
        
        db.session.commit()
        
        print(f"成功添加 {len(new_problems)} 道新题目")
        if new_problems:
            print("新增题目列表：")
            for title in new_problems:
                print(f"- {title}")
        else:
            print("没有新增题目，所有题目都已存在")

if __name__ == '__main__':
    add_mixed_problems()
